<!DOCTYPE html>

<html>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript" src="utils.js" charset="UTF-8"></script>
	<script type="text/javascript" src="wskt.js" charset="UTF-8"></script>
	<script type="text/javascript" src="paho-mqtt-1.0.1.js" charset="UTF-8"></script>
	<script type="text/javascript" src="jsonrpc.js" charset="UTF-8"></script>

	<script type="text/javascript">
        // 加载模块
        let JsonRpc = (typeof(window) !== "undefined") ? window.JsonRpc : global.JsonRpc;
    
        // 重定向日志到页面上，以便调试
        console.log = function(message) {
            txtlog.value += message + '\r\n';
        };

        //let clientId = Math.round(Math.random()*100000000).toString();
        let clientId = "web123";
        let gatewayId = '000000163E0AC954';
        let rpc;

        function openWs() {
            rpc = new JsonRpc(clientId, "ehome/gateway4/mdm/up");
			rpc.connectWs(wsurl.value);
		}

        function openMqtt() {
            let myid = "ehome/gateway4/mdm/up/" + clientId;
            rpc = new JsonRpc(myid, "ehome/gateway4/mdm/up");
			rpc.connectMqtt(mqtturl.value, myid);
		}

        function resultCallback(msg) {
            console.log(JSON.stringify(msg));
        }

        function wxLoginOrRegister() {
            let newUserInfo = {}
            rpc.rpc("ehome/gateway4/mdm/up", "token1234", "app.wxLoginOrRegister", newUserInfo, resultCallback, 10000);
        }
        
        function getUiObject(oid) {
            rpc.rpc("ehome/gateway4/mdm/down/"+gatewayId, "token1234", "app.getUiObject", {oid:0}, resultCallback, 5000);
        }

		window.onbeforeunload = function() {
			if(rpc) { rpc.close(); rpc = null; }
		}
	</script>

	<style>
		* {
			font-family: Consolas;
			font-size: 26px;
		}

		#wsurl {
			width: 920px;
		}

		#mqtturl {
			width: 920px;
		}
	</style>

	<head>
		<title>JsonRpc over WebSocket测试</title>
	</head>

	<body>
		<p>
        <input list='select' id="wsurl"   rows="1" spellcheck="false" value="ws://localhost:8504/webskt"> </input><br>
		<button onclick="openWs()">JsonRpc over WebSocket 建立连接</button>
        </p>
        <p>
		<input list='select' id="mqtturl" rows="1" spellcheck="false" value="wss://ehome.szwistar.com/mqtt/"> </input><br>
		<button onclick="openMqtt()">JsonRpc over MQTT 建立连接</button>
		</p>
        <p>
        云端 JsonRpc API:<br>
		<button onclick="wxLoginOrRegister()">wxLoginOrRegister()</button>
        </p>
        <p>
        网关 JsonRpc API:<br>
		<button onclick="getUiObject(0)">getUiObject(0)</button>
        </p>
        <p>
		<button onclick="txtlog.value = ''">消除日志</button>
		<button onclick="if(rpc) { rpc.close(); rpc = null; }">关闭连接</button>
		</p>
		<textarea id="txtlog" rows="60" cols="64" readonly="readonly"></textarea>
	</body>

</html>